package com.demo.petshop.util;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Random;

@Component
public class EmailVerificationFilter extends OncePerRequestFilter {

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        // 只拦截 /auth/send-code
        return !"/auth/send-code".equals(request.getRequestURI());
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // ...校验和发邮件逻辑...
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write("{\"msg\":\"验证码已发送\"}");
    }


    private void sendVerificationCode(String toEmail, String verificationCode) throws jakarta.mail.MessagingException {
        if (toEmail == null || toEmail.trim().isEmpty()) {
            throw new IllegalArgumentException("收件人邮箱不能为空");
        }
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("2248244079@qq.com");
        helper.setTo(toEmail);
        helper.setSubject("验证码");
        helper.setText("您的验证码是: " + verificationCode + "，请在10分钟内完成验证。", true);
        javaMailSender.send(message);
    }
}